import React, { useEffect, useState, useRef } from "react";
import {useLocation, useNavigate} from "react-router-dom";
import {
  Input,
  Tabs,
  List,
  Spin,
  message,
  Radio,
  Col,
  Row,
  Button,
  Tag,
} from "antd";
import { DownloadOutlined } from "@ant-design/icons";
import {
  searchPost,
  searchSeed,
  downloadBestSeed,
} from "../api/SearchResultApi";
import SeedDetail from "./SeedDetail"; // 导入种子详情组件
import "./SearchResult.css";

const { TabPane } = Tabs;

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

const SearchResult = () => {
  const query = useQuery();
  const keyword = query.get("keyword") || "";
  const [activeTab, setActiveTab] = useState("post");
  const [loading, setLoading] = useState(false);
  const [postResults, setPostResults] = useState([]);
  const [seedResults, setSeedResults] = useState([]);
  const [sortBy, setSortBy] = useState('createdTime');
  const [hasMore, setHasMore] = useState(true); // 添加是否有更多数据的状态
  const [selectedSeedId, setSelectedSeedId] = useState(null);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const navigate = useNavigate();
  // Pagination state
  const [searchParams, setSearchParams] = useState({
    current: 1,
    size: 12, // Default page size
  });

  // 使用 useRef 保存最后一个元素的 id
  const lastPostId = useRef(0);

  // 添加 page 状态，初始值为 1
  const [page, setPage] = useState(1);

  // 加载数据的函数
  const loadData = async () => {
    if (!keyword || loading) return;

    setLoading(true);
    try {
      if (activeTab === 'post') {
        const res = await searchPost(keyword, sortBy, searchParams.current, searchParams.size);
        const newPosts = res?.data?.postList || [];

        if (newPosts.length === 0) {
          setHasMore(false);
        } else {
          setPostResults(newPosts);
        }
      } else {
        const res = await searchSeed(keyword, searchParams.current, searchParams.size);
        const newSeeds = res?.data?.rows || [];

        if (newSeeds.length === 0) {
          setHasMore(false);
        } else {
          setSeedResults(newSeeds);
        }
      }
    } catch (error) {
      message.error("搜索失败");
    } finally {
      setLoading(false);
    }
  };

  // 监听搜索条件变化
  useEffect(() => {
    setHasMore(true);
    lastPostId.current = 0;
    setPostResults([]);
    setSeedResults([]);
    loadData();
  }, [keyword, activeTab, sortBy, searchParams.current]);

  // 添加种子点击处理函数
  const handleSeedClick = (id) => {
    setSelectedSeedId(id);
    setIsDetailModalVisible(true);
  };

  // 添加详情弹窗关闭处理函数
  const handleDetailModalClose = () => {
    setIsDetailModalVisible(false);
    setSelectedSeedId(null);
  };

  // 添加一键下载处理函数
  const handleQuickDownload = async () => {
    try {
      setLoading(true);
      const result = await downloadBestSeed(seedResults); // Pass the current seed results
      if (result.code === 200 && result.data.downloadUrl) {
        message.success(`正在下载：${result.data.seedInfo.title}`);
        // Create a hidden anchor tag to trigger the download
        const link = document.createElement('a');
        link.href = result.data.downloadUrl;
        link.download = result.data.seedInfo.title; // Use the title as the filename
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        message.error("下载失败");
      }
    } catch (error) {
      console.error("下载失败:", error);
      message.error("下载失败");
    } finally {
      setLoading(false);
    }
  };

  // Handle pagination
  const handlePagination = (direction) => {
    setSearchParams(prev => {
      const newPage = direction === 'next' ? prev.current + 1 : prev.current - 1;
      return { ...prev, current: newPage };
    });
    loadData(); // Load data for the new page
  };

  return (
    <div style={{ background: "#fff", padding: 24, minHeight: 400 }}>
      <div className="search-header">
        <h2>搜索结果：{keyword}</h2>
        {activeTab === "seed" && (
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={handleQuickDownload}
            size="middle"
            className="quick-download-btn"
          >
            一键下载种子
          </Button>
        )}
      </div>

      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: 16,
        }}
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="帖子" key="post" />
          <TabPane tab="种子" key="seed" />
        </Tabs>

        {activeTab === "post" && (
          <Radio.Group
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            buttonStyle="solid"
          >
            <Radio.Button value="createdTime">最新</Radio.Button>
            <Radio.Button value="viewCount">最热</Radio.Button>
            <Radio.Button value="commentCount">最多讨论</Radio.Button>
          </Radio.Group>
        )}
      </div>

      <Spin spinning={loading}>
        {activeTab === "post" ? (
          <List
            dataSource={postResults}
            renderItem={(item) => (
              <List.Item>
                <div>
                    <div style={{fontWeight: "bold"}}>{item.title}</div>
                    <div style={{color: "#888", fontSize: 13}} onClick={() => navigate(`/community/${item.id}`)}>
                      作者：{item.userName} | {item.likeCount}点赞 |
                      {item.viewCount}浏览
                    </div>
                  </div>
              </List.Item>
              )}
            locale={{emptyText: "暂无相关帖子"}}
            />
            ) : (
          <Row gutter={[16, 16]}>
            {seedResults.map((item) => (
              <Col span={6} key={item.id}>
                <div
                  className="seed-item"
                  onClick={() => handleSeedClick(item.id)}
                  style={{ cursor: "pointer" }}
                >
                  <h4 className="seed-title">{item.title}</h4>
                  <div className="seed-tags">
                    <Tag color="#ff6699" style={{ marginRight: '8px' }}>
                      {item.tags}
                    </Tag>
                  </div>
                  <div className="seed-meta">
                    <span className="seed-downloads">下载量: {item.userDownloadCount}</span>
                    <span className="seed-likes">点赞: {item.likeCount}</span>
                    <span className="seed-author">上传者: {item.uploadUsername}</span>
                  </div>
                  <Button type="link" href={item.downloadLink} target="_blank">
                    下载链接
                  </Button>
                </div>
              </Col>
            ))}
          </Row>
        )}

        {/* Pagination Buttons */}
        <div style={{ textAlign: 'center', marginTop: '20px' }}>
          <Button
            onClick={() => handlePagination('prev')}
            disabled={searchParams.current === 1}
          >
            上一页
          </Button>
          <Button
            onClick={() => handlePagination('next')}
            disabled={!hasMore}
            style={{ marginLeft: '10px' }}
          >
            下一页
          </Button>
        </div>
      </Spin>

      {/* 添加种子详情弹窗 */}
      {selectedSeedId && (
        <SeedDetail
          id={selectedSeedId}
          visible={isDetailModalVisible}
          onClose={handleDetailModalClose}
        />
      )}
    </div>
  );
};

export default SearchResult;
